import Taro, { Component } from '@tarojs/taro'
import { View, Text, Picker,Image ,Input} from '@tarojs/components'
import './Payment.css'
import { AtAvatar, AtList, AtListItem, AtInput, AtForm, AtButton, AtGrid,AtSearchBar,AtTag,AtTextarea } from "taro-ui"
import app from '../../main';


export default class Payment extends Component {

  config = {
    navigationBarTitleText: '快速咨询'
  }
  constructor () { 
    super(...arguments); 
    this.state = {
        value: '',
        text:'font-size: 15px ; color:#6d6d6d;' ,
        style:'font-size: 14px ; color:#000000; margin:10px 0 0 18px;',
        icon:'height:20px; width:20px; float: right; margin: 17px 5px 0 0;',
        couponSel: '无',
        couponSelector: [],
        styles:'font-size: 16px ; color:#000000; margin:15px 0 0 17px;',
        inquiry_orders:[],
        yingfukuan:'',
        youhuijuanId:'',
        obj:'',

        //img
        jiantou: 'https://zhongsheng.bayou-tech.cn/img/imgs/jiantougai.png',
        xinfeng:'https://zhongsheng.bayou-tech.cn/img/imgs/xinfeng.png',
        tianxieGrey:'https://zhongsheng.bayou-tech.cn/img/imgs/tianxieGrey.png',
        zhengquegreen:'https://zhongsheng.bayou-tech.cn/img/imgs/zhengquegreen.png',
    }
  }

  //get 下单信息
  get(){
    let me = this;
    let data = {
        type:'快速咨询'
    }
    app.post('web/myself/onOrderData', data, function(res) {
        let list = res.data.result    
        let arr = [] 
        for(let val of list.coupons){
            arr.push(val.title)
        }
        me.setState({
            inquiry_orders:list,
            couponSelector:arr,
            yingfukuan:list.totpalPrice
        })
    })
  }

  //提交订单
  post(){
    console.log(this.state.yingfukuan)
    let me = this;
    let data = {
        health_archive_id:app.dingdanid,
        inquiry_answer_id:app.inquiry_answer_id,
        type:'快速咨询',
        coupon_id:this.state.youhuijuanId
    }
    console.log('data',data)
    app.post('web/myself/mySubmitOrder', data, function(res) {
        console.log(res)
        if (res.data.status == 200) {
            let params = res.data.result.jsparams
            if(params == '' && me.state.yingfukuan <= 0){
                app.success('支付成功');
                app.redirectTo('../myOderss/myOderss?id='+res.data.result.order_id+'&state=支付跳转')
            }else{
                app.callPayment(params, function(rsp) {
                    app.success('支付成功');
                    app.redirectTo('../myOderss/myOderss?id='+res.data.result.order_id+'&state=支付跳转')
                }, function(rsp) {
                    app.toastMessage(res.data.result);
                });
            }
        } else {
            app.toastMessage(res.data.result);
        }
    })
  }

  componentWillMount(){
      this.get();
  }

    youhuijuan = e => {
        let payNuber = this.state.inquiry_orders.totpalPrice //应付费
        let discount = this.state.inquiry_orders.coupons[e.detail.value].discount  //选中的优惠券费用
        let fullMoney = this.state.inquiry_orders.coupons[e.detail.value].full_money
        let scope = this.state.inquiry_orders.coupons[e.detail.value].scope
        // console.log(scope)
        let discounts = 0//优惠
        // console.log('e',e)
        // console.log('payNuber',payNuber,'fullMoney',fullMoney)

        if(scope !='全订单可用' && scope !='非定向问诊'){
            Taro.showModal({
                title: '优惠券无法使用',
                content: '该优惠券无法在此使用',
                showCancel:false
              })
            return
        }

        if (Number(payNuber)<Number(fullMoney)){
            Taro.showModal({
                title: '优惠券无法使用',
                content: '使用条件不满足,需要满'+fullMoney+'元才可以使用!',
                showCancel:false
            })
            return
        }
        //日期校验
        let start_time = this.state.inquiry_orders.coupons[e.detail.value].start_time
        let end_time = this.state.inquiry_orders.coupons[e.detail.value].end_time
        var myDate = new Date();
        let now_time = myDate.toLocaleDateString()+" "+ myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds()
        now_time = now_time.replace("年","-","/").replace("月","-","/").replace("日","-"," "); 
        now_time = new Date(now_time.replace(/-/g, "/"))
        console.log(555,now_time)
        start_time = new Date(start_time.replace(/-/g, "/"));
        end_time = new Date(end_time.replace(/-/g, "/"));
        if(Date.parse(end_time) - Date.parse(now_time) < 0){
            Taro.showModal({
                title: '优惠券无法使用',
                content: '该优惠券已过期',
                showCancel:false
              })
            return
        }else if(Date.parse(start_time) - Date.parse(now_time) > 0){
            Taro.showModal({
                title: '优惠券无法使用',
                content: '该优惠券还未到使用日期',
                showCancel:false
              })
            return
        }



        console.log('youhuiquanstate',this.state)
        if (this.state.inquiry_orders.coupons[e.detail.value].coupon_type == "满减") {
            let arg1 = Number(payNuber)
            let arg2 = Number(discount)
            function accSubtr(arg1,arg2){
                var r1,r2,m,n;
                try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
                try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
                m=Math.pow(10,Math.max(r1,r2));
                //动态控制精度长度
                n=(r1>=r2)?r1:r2;
                return ((arg1*m-arg2*m)/m).toFixed(n);
            }
            payNuber = accSubtr(arg1,arg2)
            discounts = discount
        } else {
            let arg1 = Number(payNuber)
            let arg2 = Number(discount)
            function accMul(arg1,arg2){
                var m=0,s1=arg1.toString(),s2=arg2.toString();
                try{m+=s1.split(".")[1].length}catch(e){};
                try{m+=s2.split(".")[1].length}catch(e){};
                return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
            }

            function accDivCoupon(arg1,arg2){
                var t1=0,t2=0,r1,r2;
                try{t1=arg1.toString().split(".")[1].length;}catch(e){};
                try{t2=arg2.toString().split(".")[1].length;}catch(e){};
                r1=Number(arg1.toString().replace(".",""));
                r2=Number(arg2.toString().replace(".",""));
                return (r1/r2)*Math.pow(10,t2-t1);
            }
            let a  = accDivCoupon(arg2,100);
            payNuber = accMul(arg1,a)
            if(payNuber <=0.01){
                payNuber = 0.01
            }
        }
        this.setState({
            yingfukuan: payNuber,
            youhuijuanId:this.state.inquiry_orders.coupons[e.detail.value].id,
            couponSel:this.state.couponSelector[e.detail.value]
        },()=>{
            console.log('state',this.state.yingfukuan)
        })
        // let i = this.state.couponSelector[e.detail.value]
        // console.log(this.state.couponSelector,e.detail.value,this.state.couponSelector[e.detail.value])
        // console.log(i.indexOf('满'),i.indexOf('减'),i.indexOf('元'))
        // let a = i.substring(i.indexOf('满')+1,i.indexOf('减'))
        // let b = i.substring(i.indexOf('减')+1,i.indexOf('元'))
        // let c = this.state.inquiry_orders.totpalPrice
        // let d = ''

        // if (this.state.couponSelector[e.detail.value].coupon_type == "满减") {
        //     payNuber = payNuber - discount
        //     discounts = discount
        // } else {
        //     discounts = payNuber - (payNuber * (Number(discount) / 100))
        //     payNuber = payNuber * (Number(discount) / 100)
        // }

        // if(c > a){
        //     Taro.showModal({
        //         title: '提示',
        //         content: '不满足使用条件',
        //         showCancel:false
        //     })
        // }else{
        //     d = c - b
        //     this.setState({
        //         couponSel: this.state.couponSelector[e.detail.value],
        //         yingfukuan:d
        //     })
        // }       
    }

  render () {
    return (
      <View className='index'>

        {/*<View className='headbox'>
            <View className='box'>
                <Image className='tianxie' src={this.state.tianxieGrey}/>
                <View  className='text-a' style={this.state.text}>选择患者</View>
            </View>
            <Image className='jiantou-a' src={this.state.jiantou}/>
            <View className='box'>
                <Image className='xinfeng' src={this.state.xinfeng}/>
                <View className='text-b' style={this.state.text}>填写病情</View>
            </View>
            <Image className='jiantou-b' src={this.state.jiantou}/>
            <View className='box'>
                <Image className='zhengque' src={this.state.zhengquegreen}/>
                <View className='text-c' style={this.state.text}>支付费用</View>
            </View>         
        </View>*/}

        <AtForm className='from'>

            <AtInput
                disabled
                style='font-size:30px;'
                title='订单名称'
                type='text'
                placeholder='快速咨询'
            />

            <AtInput
                disabled
                style='font-size:30px;'
                title='咨询患者'
                type='text'
                placeholder={app.dingdanname}
            />  
        </AtForm>

        <AtForm className='from'>

            <View className='payBox'>
                <View className='pay'>应付金额</View>
                <View className='money'>{this.state.inquiry_orders.totpalPrice}元</View>
            </View>
        
        </AtForm>

        <AtList>
            <Picker mode='selector' range={this.state.couponSelector} onChange={this.youhuijuan.bind(this)}>
                <AtListItem extraText= {this.state.couponSel} arrow='right' title='可用的优惠卷' />     
            </Picker>
        </AtList>

        <View className='textBox'>
        <View className='color'>服务说明</View>
        <View className='color'>• 支付完成后即可向医生咨询，24小时内不限交流次数</View>
        <View className='color'>• 医生收到咨询后会在半小时内回复，超过半小时未回复则系统自动退款</View>
        </View>

        <View className='btnCtro'>
            <AtButton  className='leftBtn'>
                <Text>实际支付：</Text>
                <Text className='green'>{this.state.yingfukuan <= 0 ? '0' : this.state.yingfukuan}元</Text>
            </AtButton>
            <AtButton  onClick={this.post.bind(this)} className='rgihtBtn' type='primary'>立即支付</AtButton>
        </View>

      </View>
    )
  }
}
